package sim16;

/**
 * 
 */

/**
 * @author Piotr
 *
 */
public class WBStage extends PipeStage {

	public WBStage(int pipeID) {
		super(pipeID);
	}
	
	@Override
	int cycle(PipeStage prevStage) throws InvalidInstructionException {
		instr = prevStage.passInstruction();
		if (instr == null) {
			return 0;
		} else {
			if (instr.isNop()) {
				return 0;
			} else {
				instr.cycle();
				if (instr.dest1Reg != -1) {
					if (instr.dest1Reg >= 0 && instr.dest1Reg < 32) {
						doWriteBack(instr.dest1Reg, instr.getDest1Val());
					} else {
						throw new InvalidInstructionException(instr.address);
					}
				}
				if (instr.dest2Reg != -1) {
					if (instr.dest2Reg >= 0 && instr.dest2Reg < 32) {
						doWriteBack(instr.dest2Reg, instr.getDest2Val());
					} else {
						throw new InvalidInstructionException(instr.address);
					}
				}
			}
		}
		return 1;
	}

	private void doWriteBack(int destReg, int destVal) throws InvalidInstructionException {
		try {
			Sim.pipe.ids.writeBack(destReg, destVal);
		} catch (RegisterIndexOutOfBoundsException e) {
			throw new InvalidInstructionException();
		}
	}

}
